#include "Bluetooth_LE_Driver.h"

#define ESP32(args)             args"\r\n"
#define INT2STR(args)           #args 
#define INFO(fmt,arg...)        printf("[INFO] "fmt"\n",##arg)
#define ERROR(fmt,arg...)        printf("[ERROR] "fmt"\n",##arg)
typedef void(WirteT)(char*,int);

typedef void(ReadT)(char*,int);

WriteT *write_=NULL;
ReadT *read_=NULL;

char get_buffer[2048]={0};

//接口
void Init_write(void (*func)(char*,int))
{
    write_ = func;
}
void Init_read(void (*func)(char*,int))
{
    read_ = func;
}


static int BleIsOK(char* info)
{
    int ret=0;
    char* chret=NULL;

    memset(get_buffer,0,2048);
    usleep(1000000);
    ret = read_(get_buffer,2048);
    chret = strstr(get_buffer,"OK");
    if(chret)
    {
        INFO("OK");
        memset(get_buffer,0x00,ret);
        return 0;
    }   
    ERROR(info);  
    return -1;
}
int BleIsInit()
{
    char cmd[]="AT+BLEINIT?";
    char *pt=NULL;
    int ret=0;
    write_(ESP32(cmd,strlen(ESP32(cmd))));
    usleep(1000000);
    ret = read_(get_buffer,2048);
    strstr(get_buffer,":");
    if(pt)
    {
        pt++;
        switch(*pt)
        {
            case '0':{
                return 0;
            }break;
            case '1':{
                return 1;
            }break;
            case '2':{
                return 2;
            }break;
        }
    }
    ERROR("Could not get read_buffer");
    return -1;
}

int BleInit(int para)
{
    char cmd[]="AT+BLEINIT=";
    int ret=0;
    char* chret=NULL;
    strcat(INT2STR(para),cmd);
    write_(ESP32(cmd),strlen(ESP32(cmd)));
    return BleIsOK("Can not set role");
}


int BleGetDevAddr(char* addr)
{
    char cmd[]="AT+BLEADDR?";
    char addbuf[128];
    char *pt1=NULL;
    char *pt2=NULL;
    int ret=0;
    int cnt=0;

    write_(ESP32(cmd,strlen(ESP32(cmd))));
    usleep(1000000);
    ret = read_(get_buffer,2048);

    pt1 = memchr(get_buffer,':',strlen(get_buffer));
    pt2 = memchr(get_buffer,'\n',strlen(get_buffer));

    if(pt1 && pt2)
    {
        pt1++;
        while(pt1 != pt2)
        {
            
            pt1++;
            addbuf[cnt++]=*pt1;
        }
        strcpy(addr,addbuf);
        return 0;
    }
    ERROR("Could not get read_buffer");
    return -1;
}


int BleSetDevAddr(int add_type,char* random_addr)
{
    char cmd[]="AT+BLEADDR=";
    strcat(INT2STR(add_type),cmd);
    strcat(",",cmd);
    strcat(random_addr,cmd);
    write_(ESP32(cmd),strlen(ESP32(cmd)));
    return BleIsOK("Can ot Set Dev Addr");
}